package cn.mjnxin.iot.client.test;

import cn.mjnxin.iot.base.monitor.CountMonitor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 客户端处理服务端返回信息的处理器
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
@Sharable
public class TerminalHandler  extends ChannelInboundHandlerAdapter{

	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("模拟终端与网关通道建立。。。。。。");
		System.out.println("模拟终端本地ip："+ctx.channel().localAddress());
		TerminalTest.channel = ctx.channel();
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.err.println("出现异常。。。。。。。。。。"+cause.getMessage());
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf recieveMsg=(ByteBuf) msg;
		String code = ByteBufUtil.hexDump(recieveMsg).toUpperCase();//将bytebuf中的可读字节 转换成16进制数字符串
		recieveMsg.readerIndex(0);
		System.out.println("模拟终端接收总数："+CountMonitor.terminalRecieveCount.addAndGet(1)+"\n模拟终端收到数据："+code);
	}
	
}
